<template>
    <div class="circle-page">
        <!-- 顶部导航栏 -->
        <HeaderNav active-menu="circle" />

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 左侧边栏 -->
            <Sidebar :active-sidebar="activeSidebar" @sidebar-select="handleSidebarSelect" />

            <!-- 右侧内容区域 -->
            <main class="circle-main">
                <div class="circle-container">
                    <!-- 搜索区域 -->
                    <div class="search-section">
                        <!-- 搜索类型选择 -->
                        <el-select v-model="searchType" placeholder="搜索类型" style="width: 120px">
                            <el-option label="圈子名称" value="name" />
                            <el-option label="圈子类型" value="type" />
                            <el-option label="全部" value="both" />
                        </el-select>
                        <el-input v-model="searchKeyword" placeholder="搜索圈子..." class="search-input"
                            @keyup.enter="handleSearch" clearable @clear="handleClearSearch">
                            <template #prefix>
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </template>
                        </el-input>


                        <el-button type="primary" @click="handleSearch" :loading="loading">
                            搜索
                        </el-button>
                        <el-button type="success" @click="showMyCircles">
                            <el-icon>
                                <User />
                            </el-icon>
                            我的圈子
                        </el-button>
                    </div>

                    <!-- 圈子列表 -->
                    <div class="circles-list">
                        <div v-if="loading && circles.length === 0" class="loading-state">
                            <el-icon class="is-loading">
                                <Loading />
                            </el-icon>
                            <span>加载中...</span>
                        </div>

                        <template v-else>
                            <div v-for="circle in circles" :key="circle.circle_id" class="circle-item"
                                @click="goToCircleDetail(circle.circle_id)">
                                <div class="circle-content">
                                    <div class="circle-name">{{ circle.name }}</div>
                                    <div class="circle-type">{{ circle.type }}</div>
                                    <div class="circle-description">{{ circle.description }}</div>
                                    <div class="circle-stats">
                                        <span class="member-count">{{ circle.member_count }} 成员</span>
                                        <span class="post-count">{{ circle.post_count }} 帖子</span>
                                    </div>
                                </div>
                                <div class="circle-actions">
                                    <el-button v-if="circle.joined" type="danger" size="small"
                                        @click.stop="handleLeaveCircle(circle.circle_id)" :loading="circle.leaving">
                                        退出圈子
                                    </el-button>
                                    <el-button v-else type="primary" size="small"
                                        @click.stop="handleJoinCircle(circle.circle_id)" :loading="circle.joining">
                                        加入圈子
                                    </el-button>
                                </div>
                            </div>

                            <div v-if="circles.length === 0" class="empty-state">
                                <el-empty :description="emptyDescription" />
                            </div>
                        </template>
                    </div>

                    <!-- 分页组件 -->
                    <div v-if="circles.length > 0" class="pagination-section">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="false" :disabled="false" :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>
            </main>
        </div>

        <!-- 我的圈子模态框 -->
        <el-dialog v-model="myCirclesDialogVisible" title="我的圈子" width="800px" :before-close="handleCloseMyCircles">
            <MyCirclesPanel v-if="myCirclesDialogVisible" @close="myCirclesDialogVisible = false"
                @circle-updated="handleCircleUpdated" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Loading, User } from '@element-plus/icons-vue'
import { useCirclesStore } from '@/stores/circles'
import HeaderNav from '@/components/layout/HeaderNav.vue'
import Sidebar from '@/components/layout/Sidebar.vue'
import MyCirclesPanel from '@/components/circles/MyCirclesPanel.vue'

const router = useRouter()
const circlesStore = useCirclesStore()

// 响应式数据
const searchKeyword = ref('')
const searchType = ref('name') // 新增：搜索类型，默认按名称搜索
const loading = ref(false)
const isSearching = ref(false)
const activeSidebar = ref('circles')
const myCirclesDialogVisible = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 圈子列表
const circles = ref([])

// 计算空状态描述
const emptyDescription = computed(() => {
    if (isSearching.value && searchKeyword.value) {
        return `没有找到与"${searchKeyword.value}"相关的圈子`
    }
    return '暂无圈子'
})

// 侧边栏导航处理
const handleSidebarSelect = (index) => {
    activeSidebar.value = index
    switch (index) {
        case 'dashboard':
            router.push('/')
            break
        case 'social':
            router.push('/social')
            break
        case 'chat':
            router.push('/chat')
            break
        case 'lost-found':
            router.push('/lost-and-found')
            break
        case 'second-hand':
            router.push('/second-hand')
            break
        case 'network':
            router.push('/network')
            break
        case 'recruitment':
            router.push('/recruitment')
            break
        default:
            ElMessage.success(`当前已是在 ${index}页面`)
    }
}

// 显示我的圈子模态框
const showMyCircles = () => {
    myCirclesDialogVisible.value = true
}

// 关闭我的圈子模态框
const handleCloseMyCircles = () => {
    myCirclesDialogVisible.value = false
}

// 处理圈子状态更新
const handleCircleUpdated = () => {
    // 刷新主列表
    fetchCircles()
}

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
    if (!newVal && isSearching.value) {
        handleClearSearch()
    }
})

// 监听分页变化
watch([currentPage, pageSize], () => {
    if (!isSearching.value) {
        fetchCircles()
    } else {
        handleSearch()
    }
})

// 初始化加载
onMounted(() => {
    fetchCircles()
})

// 获取圈子列表
const fetchCircles = async () => {
    try {
        loading.value = true
        const response = await circlesStore.fetchCirclesAction({
            page: currentPage.value,
            pageSize: pageSize.value
        })
        if (response.code === 0) {
            circles.value = response.data.list || []
            total.value = response.data.pagination?.total || circles.value.length

            // 获取用户与圈子的关系状态
            await fetchCircleStatus()
        }
    } catch (error) {
        ElMessage.error('获取圈子列表失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 获取用户与圈子的关系状态
const fetchCircleStatus = async () => {
    if (circles.value.length === 0) return

    try {
        const circleIds = circles.value.map(circle => circle.circle_id)
        const response = await circlesStore.fetchCircleBatchStatusAction(circleIds)
        if (response.code === 0) {
            // 更新圈子的加入状态
            circles.value.forEach(circle => {
                const status = response.data[circle.circle_id]
                circle.joined = status ? status.joined : false
                circle.joining = false
                circle.leaving = false
            })
        }
    } catch (error) {
        console.error('获取圈子状态失败：', error)
    }
}

// 搜索圈子
const handleSearch = async () => {
    if (!searchKeyword.value.trim()) {
        ElMessage.warning('请输入搜索关键词')
        return
    }

    try {
        loading.value = true
        isSearching.value = true
        currentPage.value = 1 // 搜索时重置到第一页

        const response = await circlesStore.searchCirclesAction(searchKeyword.value.trim(), {
            page: currentPage.value,
            pageSize: pageSize.value,
            searchType: searchType.value // 新增：传递搜索类型参数
        })
        if (response.code === 0) {
            circles.value = response.data.list || []
            total.value = response.data.pagination?.total || circles.value.length

            // 获取用户与圈子的关系状态
            await fetchCircleStatus()

            const searchTypeText = {
                'name': '圈子名称',
                'type': '圈子类型',
                'both': '全部'
            }[searchType.value]

            ElMessage.success(`在${searchTypeText}中找到 ${total.value} 个相关圈子`)
        }
    } catch (error) {
        ElMessage.error('搜索失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 清空搜索
const handleClearSearch = () => {
    searchKeyword.value = ''
    searchType.value = 'name' // 重置搜索类型
    isSearching.value = false
    currentPage.value = 1
    fetchCircles()
}

// 每页条数变化
const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1 // 切换每页条数时回到第一页
}

// 当前页变化
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage
}

// 加入圈子
const handleJoinCircle = async (circleId) => {
    const circle = circles.value.find(c => c.circle_id === circleId)
    if (!circle) return

    try {
        circle.joining = true
        const response = await circlesStore.joinCircleAction(circleId)
        if (response.code === 0) {
            circle.joined = true
            // 重新获取数据确保计数准确
            if (isSearching.value) {
                await handleSearch()
            } else {
                await fetchCircles()
            }
            ElMessage.success('加入圈子成功')
        }
    } catch (error) {
        ElMessage.error('加入圈子失败：' + error.message)
    } finally {
        circle.joining = false
    }
}

// 退出圈子
const handleLeaveCircle = async (circleId) => {
    const circle = circles.value.find(c => c.circle_id === circleId)
    if (!circle) return

    try {
        circle.leaving = true
        const response = await circlesStore.leaveCircleAction(circleId)
        if (response.code === 0) {
            circle.joined = false
            // 重新获取数据确保计数准确
            if (isSearching.value) {
                await handleSearch()
            } else {
                await fetchCircles()
            }
            ElMessage.success('退出圈子成功')
        }
    } catch (error) {
        ElMessage.error('退出圈子失败：' + error.message)
    } finally {
        circle.leaving = false
    }
}

// 跳转到圈子详情
const goToCircleDetail = (circleId) => {
    router.push(`/circle-detail/${circleId}`)
}
</script>

<style scoped>
.circle-page {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

/* 主内容区域 */
.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.circle-main {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    margin-left: 20px;
}

.circle-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    height: calc(100vh - 80px);
    display: flex;
    flex-direction: column;
}

.search-section {
    display: flex;
    gap: 12px;
    margin-bottom: 24px;
    flex-shrink: 0;
}

.search-input {
    flex: 1;
}

.circles-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
    overflow-y: auto;
    min-height: 0;
}

.circle-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;
    flex-shrink: 0;
}

.circle-item:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}

.circle-content {
    flex: 1;
}

.circle-name {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
}

.circle-type {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
}

.circle-description {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    margin-bottom: 12px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.circle-stats {
    display: flex;
    gap: 16px;
    font-size: 12px;
    color: #999;
}

.circle-actions {
    margin-left: 16px;
    flex-shrink: 0;
}

.loading-state {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    color: #999;
    gap: 8px;
    flex: 1;
}

.empty-state {
    padding: 40px 0;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

.pagination-section {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
    display: flex;
    justify-content: center;
    flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .circle-container {
        padding: 16px;
        height: calc(100vh - 60px);
    }

    .circle-item {
        flex-direction: column;
        gap: 12px;
    }

    .circle-actions {
        margin-left: 0;
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }

    .search-section {
        flex-direction: column;
    }
}

/* 滚动条样式 */
.circles-list::-webkit-scrollbar {
    width: 6px;
}

.circles-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.circles-list::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.circles-list::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .circle-main {
        margin-left: 240px;
    }
}
</style>